from django.http import HttpResponse
from django.shortcuts import render
from .models import WriteNews,NewsCategory,Comment
from django.views.generic import View
from django.db.models import Q

def index(request):
	news = WriteNews.objects.select_related('category','author')
	categories = NewsCategory.objects.all()
	context = {
		'news':news,
		'categories':categories
	}
	return render(request,'news/index.html',context =context)


def news_category(request,category_id):
	news = WriteNews.objects.select_related('category','author').filter(category_id = category_id)
	categories = NewsCategory.objects.all()
	if news:		
		context = {
			'news':news,
			'categories':categories
		}
		return render(request,'news/news_category.html',context =context)
	else:
		context = {
			'categories':categories,
		}
		return render(request,'news/news_category.html',context = context)

def news_detail(request,new_id):
	new = WriteNews.objects.select_related('category','author').get(id = new_id)
	if request.user:
		if request.method == 'POST':
			comment = request.POST.get('comment')
			Comment.objects.create(comment=comment,news=new,author=request.user)		

	comments = Comment.objects.select_related('news','author').filter(news = new_id)
	number = comments.count()
	context = {
		'new':new,
		'comments':comments,
		'number':number,
	}
	return render(request,'news/news_detail.html',context = context)

class Search_View(View):
	def get(self,request):
		return render(request,'news/search.html')

	def post(self,request):
		contents = request.POST.get('contents')
		news = 	WriteNews.objects.select_related('category','author').\
				filter(Q(title__icontains=contents)|Q(content__icontains = contents))
		

		context = {
			'news':news
		}

		return render(request,'news/search.html',context = context)



